﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

//using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;

using Baosight.ZNH.ZMCA.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;

namespace Baosight.ZNH.ZMCA.UI.Controls
{
    public partial class DataPicker : EFView
    {
        #region 变量定义

        private IList<CheckBox> checkedTypeBoxes = new List<CheckBox>();
        private IList<CheckBox> checkedOrgBoxes = new List<CheckBox>();
        private IList<CheckBox> checkedPrjBoxes = new List<CheckBox>();

        private IList<CheckBox> allTypeBoxes = new List<CheckBox>();
        private IList<CheckBox> allOrgBoxes = new List<CheckBox>();
        private IList<CheckBox> allPrjBoxes = new List<CheckBox>();

        private CheckBox typeAllCheckBox = null;
        private CheckBox orgAllCheckBox = null;
        private CheckBox prjAllCheckBox = null;

        #endregion

        public DataPicker()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(DataPicker_Loaded);
        }

        #region 初始化控件
        /// <summary>
        /// 初始化，页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataPicker_Loaded(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("method", "initLoad");
            eiInfo.Set("service", "ZMCA20");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, InitLoadDoWorkCompleted);
        }

        /// <summary>
        /// 返回数据，绑定数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InitLoadDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询数据错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                this.UpdateData(e.EIInfo);

                //手动绑定数据
                EIInfo outInfo = e.EIInfo;
                EIBlock typeBlock = outInfo.GetBlock("cmes.ca.engineeringtype");
                EIBlock orgBlock = outInfo.GetBlock("cmes.ca.department");
                EIBlock prjBlock = outInfo.GetBlock("cmes.ca.engineering");

                if (typeBlock == null || orgBlock == null || prjBlock == null)
                {
                    return;
                }

                this.typeCheckGrid.Children.Clear();
                this.orgCheckGrid.Children.Clear();
                this.prjCheckGrid.Children.Clear();
                BindItemsToGrid(this.typeCheckGrid, typeBlock.GetRows(), "display", "TYPE");
                BindItemsToGrid(this.orgCheckGrid, orgBlock.GetRows(), "orgName", "ORG");   //初始化控件时显示全部数据
                BindItemsToGrid(this.prjCheckGrid, prjBlock.GetRows(), "fdName", "PRJ");

                this.InitQueryOrgByType();      //初始化控件时显示关联数据

            }
        }

        #endregion

        #region Telerik下拉控件事件响应

        /// <summary>
        /// 工程类型CheckBox勾选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TypeCheckBoxItemClick(object sender, RoutedEventArgs e)
        {
            CheckBox selectedBox = sender as CheckBox;

            if (selectedBox == null)
            {
                return;
            }

            if (selectedBox.IsChecked == false)
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedTypeBoxes.Clear();

                    for (int i = 0; i < this.allTypeBoxes.Count; i++)
                    {
                        allTypeBoxes[i].IsChecked = false;
                    }

                }
                else
                {
                    if (typeAllCheckBox.IsChecked == true)
                    {
                        typeAllCheckBox.IsChecked = false;
                    }

                    checkedTypeBoxes.Remove(selectedBox);
                }
            }
            else
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedTypeBoxes.Clear();

                    for (int i = 0; i < this.allTypeBoxes.Count; i++)
                    {
                        allTypeBoxes[i].IsChecked = true;
                        checkedTypeBoxes.Add(allTypeBoxes[i]);
                    }
                }
                else
                {
                    checkedTypeBoxes.Add(selectedBox);

                    if ((checkedTypeBoxes.Count == allTypeBoxes.Count) && (typeAllCheckBox.IsChecked == false))
                    {
                        typeAllCheckBox.IsChecked = true;
                    }
                }
            }
        }

        /// <summary>
        /// 工程单位CheckBox勾选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrgCheckBoxItemClick(object sender, RoutedEventArgs e)
        {
            CheckBox selectedBox = sender as CheckBox;

            if (selectedBox == null)
            {
                return;
            }

            if (selectedBox.IsChecked == false)
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedOrgBoxes.Clear();

                    for (int i = 0; i < this.allOrgBoxes.Count; i++)
                    {
                        allOrgBoxes[i].IsChecked = false;
                    }

                }
                else
                {
                    checkedOrgBoxes.Remove(selectedBox);

                    if (orgAllCheckBox.IsChecked == true)
                    {
                        orgAllCheckBox.IsChecked = false;
                    }

                }
            }
            else
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedOrgBoxes.Clear();

                    for (int i = 0; i < this.allOrgBoxes.Count; i++)
                    {
                        allOrgBoxes[i].IsChecked = true;
                        checkedOrgBoxes.Add(allOrgBoxes[i]);
                    }
                }
                else
                {
                    checkedOrgBoxes.Add(selectedBox);

                    if ((checkedOrgBoxes.Count == allOrgBoxes.Count) && (orgAllCheckBox.IsChecked == false))
                    {
                        orgAllCheckBox.IsChecked = true;
                    }
                }
            }
        }

        /// <summary>
        /// 工程名称CheckBox勾选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrjCheckBoxItemClick(object sender, RoutedEventArgs e)
        {
            CheckBox selectedBox = sender as CheckBox;

            if (selectedBox == null)
            {
                return;
            }

            if (selectedBox.IsChecked == false)
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedPrjBoxes.Clear();

                    for (int i = 0; i < this.allPrjBoxes.Count; i++)
                    {
                        allPrjBoxes[i].IsChecked = false;
                    }

                }
                else
                {
                    checkedPrjBoxes.Remove(selectedBox);

                    if (prjAllCheckBox.IsChecked == true)
                    {
                        prjAllCheckBox.IsChecked = false;
                    }
                }
            }
            else
            {
                if (selectedBox.Tag.Equals("ALL"))
                {
                    checkedPrjBoxes.Clear();

                    for (int i = 0; i < this.allPrjBoxes.Count; i++)
                    {
                        allPrjBoxes[i].IsChecked = true;
                        checkedPrjBoxes.Add(allPrjBoxes[i]);
                    }
                }
                else
                {
                    checkedPrjBoxes.Add(selectedBox);

                    if ((checkedPrjBoxes.Count == allPrjBoxes.Count) && (prjAllCheckBox.IsChecked == false))
                    {
                        prjAllCheckBox.IsChecked = true;
                    }

                }
            }
        }

        /// <summary>
        /// 工程类型下拉框关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void type_DropDownClosed(object sender, RoutedEventArgs e)
        {
            if (this.checkedTypeBoxes.Count == this.allTypeBoxes.Count)
            {
                this.type.Content = "全部";
            }
            else
            {
                this.type.Content = "选择了" + this.checkedTypeBoxes.Count.ToString() + "项";
            }

            IList<EIRow> list = this.GetCheckedPrjType();

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdType");
            JointQueryBlock(block, list, "value", "fdType");

            QueryPrjOrg(block);
        }

        /// <summary>
        /// 工程单位下拉框关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void org_DropDownClosed(object sender, RoutedEventArgs e)
        {
            if (this.checkedOrgBoxes.Count == this.allOrgBoxes.Count)
            {
                this.org.Content = "全部";
            }
            else
            {
                this.org.Content = "选择了" + this.checkedOrgBoxes.Count.ToString() + "项";
            }

            IList<EIRow> list = this.GetCheckedPrjOrg();

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdDepartmentId");

            JointQueryBlock(block, list, "orgCode", "fdDepartmentId");
            QueryPrjName(block);
        }

        /// <summary>
        /// 工程名称下拉框关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void prj_DropDownClosed(object sender, RoutedEventArgs e)
        {
            if (this.checkedPrjBoxes.Count == this.allPrjBoxes.Count)
            {
                this.prj.Content = "全部";
            }
            else
            {
                this.prj.Content = "选择了" + this.checkedPrjBoxes.Count.ToString() + "项";
            }
        }

        #endregion

        #region Telerik下拉控件添加CheckBox选择框处理方法

        /// <summary>
        /// 将信息绑定到Grid中
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="list"></param>
        /// <param name="index"></param>
        private void BindItemsToGrid(Grid gridName, IList<EIRow> list, string index, string gridType)
        {
            gridName.Children.Clear();

            switch (gridType)
            {
                case "TYPE":
                    this.allTypeBoxes.Clear();
                    this.checkedTypeBoxes.Clear();
                    break;
                case "ORG":
                    this.allOrgBoxes.Clear();
                    this.checkedOrgBoxes.Clear();
                    break;
                case "PRJ":
                    this.allPrjBoxes.Clear();
                    this.checkedPrjBoxes.Clear();
                    break;
                default:
                    break;
            }

            int count = list.Count;

            if (count > 0)
            {
                if (count > 4)
                {
                    if (count % 4 == 0)     //每行保存4个条目
                    {
                        DivRowAndColumn(gridName, count / 4, 5);    //条目数为4的整数倍
                    }
                    else
                    {
                        DivRowAndColumn(gridName, count / 4 + 1, 5);    //条目数不为4的整数倍，多添加一行
                    }
                }
                else        //默认划分为1行4列
                {
                    DivRowAndColumn(gridName, 1, 5);
                }

                AddAllItemsToGrid(gridName, list, index, gridType);
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 添加所有项目到Grid中（包含“全部”勾选框）
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="list"></param>
        /// <param name="index"></param>
        private void AddAllItemsToGrid(Grid gridName, IList<EIRow> list, string index, string gridType)
        {
            int rowIndex = 0;
            int colIndex = 0;

            if (list.Count > 0)     //添加“全部”选择框
            {
                StackPanel stack = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };

                CheckBox check = new CheckBox() { DataContext = list, Tag = "ALL" };
                check.IsChecked = true;
                check.Content = "全部";
                switch (gridType)
                {
                    case "TYPE":
                        typeAllCheckBox = check;
                        check.Click += new RoutedEventHandler(TypeCheckBoxItemClick);
                        break;
                    case "ORG":
                        orgAllCheckBox = check;
                        check.Click += new RoutedEventHandler(OrgCheckBoxItemClick);
                        break;
                    case "PRJ":
                        prjAllCheckBox = check;
                        check.Click += new RoutedEventHandler(PrjCheckBoxItemClick);
                        break;
                    default:
                        break;
                }
                stack.Children.Add(check);

                stack.SetValue(Grid.RowProperty, rowIndex);
                stack.SetValue(Grid.ColumnProperty, colIndex++);
                gridName.Children.Add(stack);
            }
            else
            {
                return;
            }

            AddItemsToGrid(gridName, list, index, gridType);
        }

        /// <summary>
        /// 添加查询到的项目到Grid中（不包含“全部”勾选框）
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="list"></param>
        /// <param name="index"></param>
        private void AddItemsToGrid(Grid gridName, IList<EIRow> list, string index, string gridType)
        {
            int rowIndex = 0;
            int colIndex = 1;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i][index] == null || list[i][index].ToString().Trim().Equals(""))
                    continue;

                StackPanel stack = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Margin = new Thickness(5, 5, 5, 5)
                };

                CheckBox check = new CheckBox() { DataContext = list[i], Tag = gridType };
                check.IsChecked = true;
                check.Content = list[i][index].ToString().Trim();
                switch (gridType)
                {
                    case "TYPE":
                        check.Click += new RoutedEventHandler(TypeCheckBoxItemClick);
                        this.allTypeBoxes.Add(check);
                        this.checkedTypeBoxes.Add(check);
                        break;
                    case "ORG":
                        check.Click += new RoutedEventHandler(OrgCheckBoxItemClick);
                        this.allOrgBoxes.Add(check);
                        this.checkedOrgBoxes.Add(check);
                        break;
                    case "PRJ":
                        check.Click += new RoutedEventHandler(PrjCheckBoxItemClick);
                        this.allPrjBoxes.Add(check);
                        this.checkedPrjBoxes.Add(check);
                        break;
                    default:
                        break;
                }

                stack.Children.Add(check);
                stack.SetValue(Grid.RowProperty, rowIndex);
                stack.SetValue(Grid.ColumnProperty, colIndex++);
                gridName.Children.Add(stack);

                if (colIndex == 5)
                {
                    colIndex = 1; rowIndex++;
                }
            }
        }

        /// <summary>
        /// 将指定的Grid划分成行列
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="rowCount"></param>
        /// <param name="colCount"></param>
        private void DivRowAndColumn(Grid gridName, int rowCount, int colCount)
        {
            if (rowCount <= 0 || colCount <= 0)
            {
                rowCount = 1;
                colCount = 1;
            }
            else
            {
                for (int i = 0; i < rowCount; i++)
                {
                    gridName.RowDefinitions.Insert(i, new RowDefinition() { Height = GridLength.Auto });
                }
                for (int j = 0; j < colCount; j++)
                {
                    gridName.ColumnDefinitions.Insert(j, new ColumnDefinition() { Width = GridLength.Auto });
                }
            }
        }

        #endregion

        #region Telerik下拉控件之间关联、刷新函数

        /// <summary>
        /// 工程单位查询
        /// </summary>
        /// <param name="block"></param>
        private void QueryPrjOrg(EIBlock block)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.AddBlock(block);
            inInfo.Set("method", "queryProjectOrg");
            inInfo.Set("service", "ZMCA20");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(inInfo, QueryPrjOrgDoWorkCompleted);
        }

        /// <summary>
        /// 工程单位查询结果回调事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryPrjOrgDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                return;
            }
            else
            {
                EIBlock block = e.EIInfo.GetBlock("org");
                BindItemsToGrid(this.orgCheckGrid, block.GetRows(), "orgName", "ORG");

                this.InitQueryNameByOrg();
            }
        }

        /// <summary>
        /// 工程单位查询
        /// </summary>
        /// <param name="block"></param>
        private void QueryPrjName(EIBlock block)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.AddBlock(block);
            inInfo.Set("method", "queryProjectName");
            inInfo.Set("service", "ZMCA20");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(inInfo, QueryPrjNameDoWorkCompleted);
        }

        /// <summary>
        /// 工程名称查询结果回调事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryPrjNameDoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                return;
            }
            else
            {
                EIBlock block = e.EIInfo.GetBlock("eng");
                BindItemsToGrid(this.prjCheckGrid, block.GetRows(), "fdName", "PRJ");
            }
        }

        /// <summary>
        /// 拼接查询字段
        /// </summary>
        /// <param name="block"></param>
        /// <param name="list"></param>
        /// <param name="sourIndex"></param>
        /// <param name="destIndex"></param>
        private void JointQueryBlock(EIBlock block, IList<EIRow> list, string sourIndex, string destIndex)
        {
            string fdIndex = "''";

            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                    {
                        if ((list[0][sourIndex] == null) || (list[0][sourIndex].ToString().Trim().Equals("")))
                        {
                            continue;
                        }
                        else
                        {
                            fdIndex = "'" + list[0][sourIndex].ToString().Trim() + "'";
                        }
                    }
                    else
                    {
                        if ((list[i][sourIndex] == null) || (list[i][sourIndex].ToString().Trim().Equals("")))
                        {
                            continue;
                        }
                        else
                        {
                            fdIndex = fdIndex + ", '" + list[i][sourIndex].ToString().Trim() + "'";
                        }
                    }
                }
            }

            EIRow row = new EIRow();
            row.Add(destIndex, fdIndex);

            block.AddRow(row);
        }

        #endregion

        #region Telerik下拉控件对外接口

        /// <summary>
        ///获取工程类型
        /// </summary>
        public IList<EIRow> GetCheckedPrjType()
        {
            IList<EIRow> list = new List<EIRow>();

            if (this.checkedTypeBoxes.Count > 0)
            {
                for (int i = 0; i < this.checkedTypeBoxes.Count; i++)
                {
                    EIRow row = checkedTypeBoxes[i].DataContext as EIRow;

                    list.Add(row);
                }

                return list;

            }
            else
            {
                return list;
            }
        }

        /// <summary>
        /// 判断工程类型是否是全选
        /// </summary>
        public bool IsCheckedAllPrjType()
        {
            if (this.checkedTypeBoxes.Count == this.allTypeBoxes.Count)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///获取工程单位
        /// </summary>
        public IList<EIRow> GetCheckedPrjOrg()
        {
            IList<EIRow> list = new List<EIRow>();

            if (this.checkedOrgBoxes.Count > 0)
            {
                for (int i = 0; i < this.checkedOrgBoxes.Count; i++)
                {
                    EIRow row = checkedOrgBoxes[i].DataContext as EIRow;

                    list.Add(row);
                }

                return list;

            }
            else
            {
                return list;
            }
        }

        /// <summary>
        /// 判断工程单位是否是全选
        /// </summary>
        public bool IsCheckedAllPrjOrg()
        {
            if (this.checkedOrgBoxes.Count == this.allOrgBoxes.Count)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///获取工程名称
        /// </summary>
        public IList<EIRow> GetCheckedPrjName()
        {
            IList<EIRow> list = new List<EIRow>();

            if (this.checkedPrjBoxes.Count > 0)
            {
                for (int i = 0; i < this.checkedPrjBoxes.Count; i++)
                {
                    EIRow row = checkedPrjBoxes[i].DataContext as EIRow;

                    list.Add(row);
                }

                return list;

            }
            else
            {
                return list;
            }
        }

        /// <summary>
        /// 判断工程名称是否是全选
        /// </summary>
        public bool IsCheckedAllPrjName()
        {
            if (this.checkedPrjBoxes.Count == this.allPrjBoxes.Count)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region Telerik控件其它：初始化控件时全选关联

        /// <summary>
        /// 
        /// </summary>
        private void InitQueryOrgByType()
        {
            IList<EIRow> typeList = this.GetCheckedPrjType();

            EIBlock block = new EIBlock("queryBlock");

            Common.AddColumnToBlock(block, "fdType");
            JointQueryBlock(block, typeList, "value", "fdType");

            QueryPrjOrg(block);
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitQueryNameByOrg()
        {
            IList<EIRow> list = this.GetCheckedPrjOrg();
            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdDepartmentId");

            JointQueryBlock(block, list, "orgCode", "fdDepartmentId");
            QueryPrjName(block);
        }

        #endregion


    }
}
